import service from '@/request'
import { asynchronousRouter } from '@/router/asynchronousRouter/index'
import { cloneDeep } from 'lodash-es'
import router from '@/router/index'
const userAuth = {
  namespaced: true,
  state: {
    // 用户菜单列表
    userMenuList: [],
    // 用户权限列表
    userPermissions: [],
    // 用户信息
    userInfo: {},
    // 用户token
    token: localStorage.getItem('tokens') || ''
  },
  mutations: {
    SET_USER_MENU_LIST(state, userMenuList) {
      state.userMenuList = userMenuList
    },
    SET_USER_PERMISSIONS(state, userPermissions) {
      state.userPermissions = userPermissions
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
    },
    CLEAR_STATE(state) {
      state.userMenuList = []
      state.userPermissions = []
      state.userInfo = {}
      state.token = ''

      localStorage.removeItem('tokens')
      localStorage.removeItem('vuex')
    }
  },
  actions: {
    // 获取用户菜单列表
    async getUserPermissions({ commit }) {
      try {
        let res = await service.post('/api/auth1')
        // 过滤用户权限 深度拷贝已有权限
        let filterRouters = filterRouter(res.roles, cloneDeep(asynchronousRouter))
        //添加路由
        filterRouters.forEach(route => {
          router.addRoute(route)
        })
        // 本地存储用户路由信息
        localStorage.setItem('userRouters', JSON.stringify(filterRouters))
        // 存储用户权限列表
        commit('SET_USER_PERMISSIONS', res.roles)
        // 存储用户菜单列表
        commit('SET_USER_MENU_LIST', filterRouters)
      } catch (error) {
        console.log(error)
      }
    },
    // 获取用户信息
    async getUserInfo({ commit, state }, { username, password }) {
      let res = await service.post('/api/login1', {
        data: {
          username,
          password
        }
      })
      // 本地存储tokens
      localStorage.setItem('tokens', res.tokens)
    }
  }
}

function filterRouter(userAuth, dynamicRouter) {
  // 遍历动态路由的每一项
  return dynamicRouter.filter(route => {
    // 判断路由是否存在权限要求
    if (route.meta && route.meta.permission) {
      // 对比用户权限得到过滤后的路由
      const hasAccess = route.meta.permission.some(role => userAuth.includes(role))
      // 过滤子路由将子路由作为新对象属性
      if (hasAccess && route.children) {
        route.children = filterRouter(userAuth, route.children)
      }
      // 返回最终路由
      return hasAccess
    }
    return true
  })
}

export default userAuth
